# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VulnerabilityIssueLinks::BulkCreateService, feature_category: :vulnerability_management do
  include AccessMatchersGeneric

  before do
    stub_licensed_features(security_dashboard: true)
  end

  let_it_be(:user) { create(:user) }
  let_it_be(:project) { create(:project) }
  let_it_be(:vulnerabilities) { create_list(:vulnerability, 2, project: project) }
  let_it_be(:issue) { create(:issue, project: project) }

  let(:service) { described_class.new(user, issue, vulnerabilities) }

  subject(:bulk_create_issue_links) { service.execute }

  context 'with an authorized user with proper permissions' do
    before do
      project.add_developer(user)
    end

    context 'with valid params' do
      it 'creates Vulnerabilities::IssueLink objects' do
        expect { bulk_create_issue_links }.to change { Vulnerabilities::IssueLink.count }.by(2)
      end
    end

    context 'if the issue links already exist' do
      before do
        create(:vulnerabilities_issue_link, :related, vulnerability: vulnerabilities.first, issue: issue)
        create(:vulnerabilities_issue_link, :related, vulnerability: vulnerabilities.last, issue: issue)
      end

      it "doesn't fail" do
        response = bulk_create_issue_links
        expect(response).to be_success
      end

      it "doesn't create new IssueLinks" do
        expect { bulk_create_issue_links }.not_to change { Vulnerabilities::IssueLink.count }
      end
    end

    context 'with missing vulnerabilities' do
      let(:service) { described_class.new(user, issue, nil) }

      it "doesn't create vulnerabilities::IssueLink objects" do
        expect { bulk_create_issue_links }.not_to change { Vulnerabilities::IssueLink.count }
      end

      it "responds with an error" do
        response = bulk_create_issue_links
        expect(response).to be_error
      end
    end

    context 'with missing issue' do
      let(:service) { described_class.new(user, nil, vulnerabilities) }

      it "doesn't create vulnerabilities::IssueLink objects" do
        expect { bulk_create_issue_links }.not_to change { Vulnerabilities::IssueLink.count }
      end

      it "responds with an error" do
        response = bulk_create_issue_links
        expect(response).to be_error
      end
    end
  end
end
